package com.all.diy
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.view.View.OnLongClickListener
import android.webkit.JavascriptInterface
import android.webkit.ValueCallback
import android.webkit.WebView
import android.widget.Button
import android.widget.FrameLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.all.diy.utils.CustomPopup
import com.all.diy.utils.PopupInteractionListener
import com.all.diy.utils.StorageUtils
import com.blankj.utilcode.util.SPUtils
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import com.lxj.xpopup.XPopup
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File

class MainActivity : AppCompatActivity(), PopupInteractionListener {
    private var uploadCallback: ValueCallback<Array<Uri>>? = null
    private val REQUEST_CAMERA = 1008
    private val REQUEST_GALLERY = 1009
    private val REQUEST_CAMERA_XITONG = 1010
    private var takeType = 1 // 1:拍照 2：相册
    private var handler = Handler(Looper.getMainLooper())
    private lateinit var agentWeb: AgentWeb;
    private var setting_bt: Button? = null
    private var deviceId: String= "100305"
    //private var loadUrlhost: String= "http://192.168.31.31:8082/#/";
    private var loadUrlhost: String= "https://design.yunweiyin.com/#/";
    private var loadUrl: String= "$loadUrlhost?device_id=$deviceId&is_APP=1"
    private var spUtils: SPUtils = SPUtils.getInstance();

    @SuppressLint("MissingInflatedId", "SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (!PermissionUtils.checkPermissions(this, REQUIRED_PERMISSIONS)) {
            PermissionUtils.requestPermissions(this, REQUIRED_PERMISSIONS)
        }
        val context = this
        GlobalScope.launch(Dispatchers.IO) {
            StorageUtils.cleanOldFiles(context, 1) // 每天清理一次
        }
        deviceId = spUtils.getString("deviceId", "100305");
        setting_bt = findViewById(R.id.setting_bt)
        loadUrl= "$loadUrlhost?device_id=$deviceId&is_APP=1"
        agentWeb = AgentWeb.with(this)
            .setAgentWebParent(findViewById(R.id.webView), FrameLayout.LayoutParams(-1, -1))
            .useDefaultIndicator(Color.parseColor("#00000000"), 0)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .createAgentWeb()
            .ready()
            .go(loadUrl)

        //获取WebView并设置相关属性
        val webView: WebView = agentWeb.getWebCreator().getWebView()
        webView.isVerticalScrollBarEnabled = false // 隐藏垂直滚动条
        webView.isHorizontalScrollBarEnabled = false // 隐藏水平

        agentWeb?.getWebCreator()?.webView?.webChromeClient = object : WebChromeClient() {
            override fun onShowFileChooser(
                webView: WebView,
                filePathCallback: ValueCallback<Array<Uri>>,
                fileChooserParams: FileChooserParams
            ): Boolean {
                uploadCallback = filePathCallback
                showImagePickerDialog()
                return true
            }
            override fun onProgressChanged(view: WebView, newProgress: Int) {

            }
        }
        agentWeb.getAgentWebSettings()?.webSettings?.javaScriptEnabled = true
        agentWeb.getJsInterfaceHolder()?.addJavaObject("android", YourJavaScriptInterface())
        setting_bt?.setOnLongClickListener(OnLongClickListener {
            showPop()
            false
        })
    }

    private fun showPop() {
        XPopup.Builder(this@MainActivity)
            .autoDismiss(false)     //点击外部不消失
            .isCenterHorizontal(true)
            .asCustom(CustomPopup(this@MainActivity, this, deviceId))
            .show()
    }

    private fun showImagePickerDialog() {
        Log.i("takeType",takeType.toString());
        handler.postDelayed({
            if (takeType == 1) {
                val intent = Intent(this@MainActivity, UVCCameraActivity::class.java)
                startActivityForResult(intent, REQUEST_CAMERA)
                //openCamera();
            } else {
                openImageChooser()
            }
        }, 150) // 延迟3秒
    }


    private lateinit var cameraImageUri: Uri;
    private fun openCamera() {
        try {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            val photoFile = createImageFile()
            cameraImageUri = FileProvider.getUriForFile(this, "com.all.diy.provider", photoFile)
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri)
            startActivityForResult(intent, REQUEST_CAMERA_XITONG)
        } catch (e: Exception) {
            Log.i("openCamera",e.toString());
        }
    }


    private fun createImageFile(): File {
        //val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        //val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        var photoFile = File(StorageUtils.getSafeExternalFilesDir(this, null),System.currentTimeMillis().toString() + ".jpg")
        return photoFile
    }


    //打开相册选择器
    private fun openImageChooser() {
        try {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "image/*"
            startActivityForResult(Intent.createChooser(intent, ""), REQUEST_GALLERY)
           } catch (e: Exception) {
        }
    }

    override fun onConfirmClick(machine_id: String, isChecked: Boolean) {
        deviceId = machine_id;
        spUtils.put("deviceId", deviceId);
        loadUrl = "$loadUrlhost?device_id=$deviceId&is_APP=1"
        Log.i("loadUrl",loadUrl);
        agentWeb = AgentWeb.with(this)
            .setAgentWebParent(findViewById(R.id.webView), FrameLayout.LayoutParams(-1, -1))
            .useDefaultIndicator(Color.parseColor("#00000000"), 0)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .createAgentWeb()
            .ready()
            .go(loadUrl)
        // 获取WebView并设置相关属性
        val webView: WebView = agentWeb.getWebCreator().getWebView()
        webView.isVerticalScrollBarEnabled = false // 隐藏垂直滚动条
        webView.isHorizontalScrollBarEnabled = false // 隐藏水平
        handler.postDelayed({
            if(isChecked){
                agentWeb.jsAccessEntrace.callJs("openVConsole()")
            }else{
                agentWeb.jsAccessEntrace.callJs("closeVConsole()")
            }
        }, 1000) // 延迟3秒
    }

    override fun onDismissed() {

    }

    inner class YourJavaScriptInterface {
        @JavascriptInterface  //注意这个注解对于Android < 4.2版本是必须的，从4.2开始可以省略。
        fun takePhoto(type: Int) {
            takeType = type
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            //1. 基础校验：结果码与回调有效性
            if (resultCode != RESULT_OK || uploadCallback == null) {
                //Toast.makeText(this@MainActivity, "获取图片失败", Toast.LENGTH_LONG).show()
                uploadCallback?.onReceiveValue(null)
                uploadCallback = null
                return
            }
            //2. 初始化结果数组
            //3. 处理相机返回结果
            if (requestCode == REQUEST_CAMERA_XITONG) {
                arrayOf(cameraImageUri).let { uploadCallback?.onReceiveValue(it) };
            }
            if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
                val url = data?.getStringExtra("url") ?: return
                val file = File(url)
                if (!file.exists()) {
                    uploadCallback?.onReceiveValue(null)
                    uploadCallback = null
                    return //文件存在性检查
                }
                uploadCallback?.onReceiveValue(arrayOf(Uri.fromFile(file)))
                Log.e("file11",file.path);
                //agentWeb!!.jsAccessEntrace.callJs("sendToVue('" + file+ "')");
            } else if (requestCode == REQUEST_GALLERY && data != null) { // //4. 处理相册返回结果
                val dataUrl = data.data;
                if (dataUrl!=null){
                    uploadCallback?.onReceiveValue(arrayOf(dataUrl));
                }else{
                    uploadCallback?.onReceiveValue(null)
                }
                //val contentUri =  Uri.parse(dataUrl.toString());
                //val file2 = Uri.fromFile(File(UriToFileUtil.getPath(this, contentUri)));
                //file2.path?.let { Log.e("file11", it) };
                //val contentUri =  Uri.parse("content://com.android.providers.media.documents/document/image%3A316")
                //val projection = arrayOf(MediaStore.Images.Media.DATA) // 这里我们只查询图片的路径
                //agentWeb!!.jsAccessEntrace.callJs("sendToVue('" + data+ "')");
            }
            uploadCallback = null
        } catch (e: Exception) {
            // 异常处理（可扩展日志记录）
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (PermissionUtils.handlePermissionResult(requestCode, permissions, grantResults)) {
            //Toast.makeText(this, "所有权限已授予", Toast.LENGTH_SHORT).show();
            StorageUtils.getAppExternalRootDir(this) // 初始化根目录
            // 在后台线程执行清理
        } else {
            Toast.makeText(this, "部分权限被拒绝", Toast.LENGTH_SHORT).show()
            openAppSettings()
        }
    }

    private fun openAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.parse("package:$packageName")
        startActivity(intent)
    }

    companion object {
        private val REQUIRED_PERMISSIONS = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
             Manifest.permission.RECORD_AUDIO,
        )
    }

    private var backPressedOnce = false

    override fun onBackPressed() {
        if (backPressedOnce) {
            super.onBackPressed()
            return
        }
        this.backPressedOnce = true
        agentWeb?.getWebCreator()?.getWebView()?.goBack();
        Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
        Handler(Looper.getMainLooper()).postDelayed({
            backPressedOnce = false
        }, 1200)
    }


}